package com.zlq.login.controllermvc;

import com.zlq.login.entity.User;
import com.zlq.login.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import javax.annotation.Resource;
import java.util.List;

@Controller
public class UserController {
    @Resource
    private UserService userService;
//    private static final UserDaoLo ud=new UserDaoLo();

    @RequestMapping("/list")
    public String listAll(@RequestParam(required = false) int pageNum, int page, Model model){
//        page=page==0?3:page;
        List<User> users = null;
        try {
            users = userService.selectByPage(pageNum,page);
            Integer total = userService.selectCount();
            model.addAttribute("total",total);
            Integer to= (total/page);
            model.addAttribute("to",to);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("pageNum",pageNum);
//        model.addAttribute("page",page);
        model.addAttribute("users", users );
        return "listUser";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(int id, Model model){
        try {
            User user = userService.selectById(id);
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "update";
    }

    @RequestMapping("/update")
    public String update(User user){

        userService.update(user);
        return "redirect:/list?pageNum=0&page=3";
    }

    @RequestMapping("/delete")
    public String delete(User user){
        userService.delete(user.getId());
        return "redirect:/list?pageNum=0&page=3";
    }

    @RequestMapping("/saveUser")
    public String saveUser(){
        return "saveUser";
    }


    @RequestMapping("/insert")
    public String save(User user){
        userService.save(user);
        return "redirect:/list?pageNum=0&page=3";
    }

    @RequestMapping("/search")
    public String search(String str,Model model){
        List<User> us = userService.selectByLike("%" + str + "%");
        model.addAttribute("us",us);
        return "search";
    }



}
